/**
 * 报事评价
 * @author levy
 */
import {health} from "../const/offices";
import {prefix} from "../const/prefix";

(function (lf, r) {
    var ajax = lf.utils.ajax,
        api = health.api,
        apiUrl = prefix.oldpeople,
        dataId,
        doClose = lf.bridgeJs.doClose;
    var imgUrl = "../public/images/reportComment/";

    /**
     * 函数里要里用到的变量
     * degree 满意度
     * trantimely 及时处理
     * tranresult 处理结果
     * workerinfo 参与人评价信息:name-id-type-评价(1,不满意;2,满意),
     *            由workers与infos组合而成.
     *            调用时需要传给后台前,需要调用一下toString()方法
     */
    var degree = 2,
        trantimely = '',
        tranresult = '',
        workerinfo = [],
        workers = [],
        infos = [],
        content = '',
        btn = 'blue',
        flag = lf.utils.getUrlParam('flag'),
        eventId = lf.utils.getUrlParam('eventId');

    const FINGER = 'finger';

    var Satisfaction = React.createClass({
        getInitialState: function () {
            return ({});
        },
        click: function (e) {
            if (e.target.className == 'radio') {
                $(e.target).siblings().filter('.radio').attr('src', imgUrl + "radio.png");
                e.target.src = imgUrl + 'radio_active.png';
                degree = e.target.getAttribute('data-index');
            } else {
                $(e.target).siblings().filter('.radio').attr('src', imgUrl + "radio.png");
                e.target.previousSibling.src = imgUrl + 'radio_active.png';
                degree = e.target.previousSibling.getAttribute('data-index');
            }
        },

        render: function () {
            return (
                <div className="satisfaction ">
                    <span className="bold">满意度</span>
                    <div className="inlineBlock">
                        <img onTouchStart={this.click} data-index='2' className="radio"
                             src={imgUrl + "radio_active.png"}/>
                        <img onTouchStart={this.click} className="radioImg" src={imgUrl + "good.png"} data-to="radio"/>
                        <img onTouchStart={this.click} data-index='1' className="radio" src={imgUrl + "radio.png"}/>
                        <img onTouchStart={this.click} className="radioImg" src={imgUrl + "so-so.png"} data-to="radio"/>
                        <img onTouchStart={this.click} data-index='0' className="radio" src={imgUrl + "radio.png"}/>
                        <img onTouchStart={this.click} className="radioImg" src={imgUrl + "bad.png"} data-to="radio"/>
                    </div>
                </div>
            );
        }
    });

    var WorkFlow = React.createClass({
        getInitialState: function () {
            var data = this.props.data;
            workers.push(data.id + '-');

            return ({
                isSatisfied: false,
            });
        },
        click: function (e) {
            var agree = !this.state.isSatisfied;
            this.setState({isSatisfied: agree});//一旦改变state,就重调render,故workers不能在render里
            if (agree) {
                e.target.src = imgUrl + "red_heart.png";
            }
            else {
                e.target.src = imgUrl + "heart.png";
            }
        },

        render: function () {
            var heart = imgUrl + "heart.png";
            var redHeart = imgUrl + "red_heart.png";

            var data = this.props.data,
                index = this.props.index;
            var role = index == 0 ? '项目负责人' : '参与人';

            return (
                <div className="bg-f2 border-top flex-box-row">
                    <span className="gray-font item">{data.name}</span>
                    <span className="gray-font item">{role}</span>
                    <span className="item"></span>
                    <img onTouchStart={this.click} src={this.state.isSatisfied == true ? redHeart : heart}/>
                </div>
            );
        }
    });

    var Score = React.createClass({
        selectFlower: function (e) {
            var data = e.target.getAttribute("data-select").split('-');
            var type = data[0],
                index = data[1];

            var $bro = $(e.target).siblings();//兄弟,不包括自己
            //第一个是span,要排除在外
            for (var j = 1; j < $bro.length; j++) {
                var i = $bro[j].getAttribute("data-select").split('-')[1];
                if (i < index) {
                    $bro[j].src = imgUrl + "red_flower.png";
                } else {
                    $bro[j].src = imgUrl + "flower.png";
                }
            }
            e.target.src = imgUrl + "red_flower.png";

            if (type == 'trantimely') {
                trantimely = index;
            }
            else {
                tranresult = index;
            }

        },
        getInitialState: function () {
            return ({
                workflowList: [],
            });
        },
        componentWillMount: function () {
            ajax({
                url: apiUrl + api.workflow,
                type: 'POST',
                data: {
                    eventId: eventId,
                },
                headers: {
                    openId: dataId.openId,
                },
                success: function (data) {
                    data = data.dataList;

                    var workflowList = data.map(function (data, index) {
                        return <WorkFlow data={data} index={index}/>
                    });
                    this.setState({workflowList: workflowList});
                }.bind(this)
            });

        },
        render: function () {
            var flowerUrl = "../public/images/reportComment/flower.png";

            return (
                <div className="score border-bottom">
                    <div className="">
                        <span className="bold">动态评分</span>
                        <div className="give-score">
                            <div>
                                <span className="gray-font">及时处理</span>
                                <img onClick={this.selectFlower} data-select="trantimely-1" src={flowerUrl}/>
                                <img onClick={this.selectFlower} data-select="trantimely-2" src={flowerUrl}/>
                                <img onClick={this.selectFlower} data-select="trantimely-3" src={flowerUrl}/>
                                <img onClick={this.selectFlower} data-select="trantimely-4" src={flowerUrl}/>
                                <img onClick={this.selectFlower} data-select="trantimely-5" src={flowerUrl}/>
                            </div>
                            <div>
                                <span className="gray-font">处理结果</span>
                                <img onClick={this.selectFlower} data-select="tranresult-1" src={flowerUrl}/>
                                <img onClick={this.selectFlower} data-select="tranresult-2" src={flowerUrl}/>
                                <img onClick={this.selectFlower} data-select="tranresult-3" src={flowerUrl}/>
                                <img onClick={this.selectFlower} data-select="tranresult-4" src={flowerUrl}/>
                                <img onClick={this.selectFlower} data-select="tranresult-5" src={flowerUrl}/>
                            </div>
                        </div>
                    </div>
                    <div className="workflow border-bottom">
                        {this.state.workflowList}
                    </div>
                </div>
            );
        }
    });
    var Comment = React.createClass({
        render: function () {
            return (
                <div className="comment border-bottom">
                    <p className="bold comment-text">评价</p>
                    <textarea className="" name="comment" id="comment" placeholder="您好,请发表下您的建议" required></textarea>
                </div>
            );
        }
    });


    var ReportComment = React.createClass({
        getInitialState: function () {
            return {
                data: [
                    {
                        imgUrl: '../public/images/rush/unconnected.png'
                    }
                ],
            }
        },

        componentWillMount: function () {
        },
        //对人的评价
        getInfos: function () {
            infos.length = 0;//清空数组
            var $imgList = $('.workflow').find('img');
            for (var i = 0; i < $imgList.length; i++) {
                var img = $imgList[i];
                if (img.src.indexOf('red_heart') == -1) {
                    infos.push(0);
                }
                else {
                    infos.push(1);
                }
            }
            return infos;
        },
        //组成 id-num 字符串
        setupWorkerinfo: function () {
            infos = this.getInfos();
            if (infos.length == 0 || infos.length != workers.length) {
                return false;
            }

            workerinfo.length = 0;//以免点击多次而多次存放数据
            for (var i = 0; i < infos.length; i++) {
                workerinfo.push(workers[i] + infos[i]);
            }

            return true;
        },
        checkSubmit: function () {

            if (trantimely < 1 || tranresult < 1) return false;

            content = ($('#comment').val() == "") ? true : false;

            if (content) {
                content = "";
                return false;
            } else {
                content = $('#comment').val();
            }

            return this.setupWorkerinfo();

        },
        submit: function () {
            if (flag == FINGER) {
               var apiAdd = lf.finger.api.event.accepterEval;
            } else {
                var api = apiUrl + '/api/work/event/createEventAccepterEval'; ///lf.api.report.comment;
            }

            if (this.checkSubmit()) {
                ajax({
                    url:api,
                    type: 'post',
                    contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
                    data: {
                        eventId: eventId,
                        attitude: degree,
                        timeliness: trantimely,
                        level: tranresult,
                        result: content,
                        accepterLikes: workerinfo.toString(),
                    },
                    headers: {
                        openId: dataId.openId,
                    },
                    success: function (data) {
                        console.log(dataId.openId)
                        if (data.code == '200') {
                            mui.toast('评价成功');
                            doClose();
                        }
                        else {
                            alert('评价失败,请重试!');
                        }
                    }

                });

            } else {
                mui.toast('请先完善评价');
            }

            return;
        },


        //父组件传data给子组件
        render: function () {
            return (
                <div className="report-comment">
                    <Satisfaction/>
                    <Score />
                    <Comment/>
                    <div className="bg-f2">
                        <button onClick={this.submit}
                                className={(flag == FINGER ? btn : 'lf-green-btn')+ ' mui-btn form-submit-btn'}>确认提交
                        </button>
                    </div>
                </div>
            );

        }
    });

    lf.appJs.getUser(function (user) {
        ajax({
            url: apiUrl + api.getGlobalId,
            type: 'post',
            data: {
                custGlobalId: user.globalId || user.custLoginVo.globalId,//user.id,'C1606281657108af41b8e068927' ||
            },
            success: function (data) {
                dataId = data.data;

                r.render(
                    <ReportComment user={user}/>,
                    document.getElementById('root'),
                    function () {

                    }
                )
            }
        })
    })

})(liefeng, React)
